package com.wms.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wms.ymcc.api.LoginApi;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.domain.Login;
import com.wms.ymcc.domain.User;
import com.wms.ymcc.domain.UserAccount;
import com.wms.ymcc.domain.UserBaseInfo;
import com.wms.ymcc.dto.PhoneRegisterDto;
import com.wms.ymcc.mapper.UserMapper;
import com.wms.ymcc.pojo.VerifyCode;
import com.wms.ymcc.result.JSONResult;
import com.wms.ymcc.service.IUserAccountService;
import com.wms.ymcc.service.IUserBaseInfoService;
import com.wms.ymcc.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author 阿盛哟
 * @since 2025-05-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {



    //private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private LoginApi loginApi;//  远程调用uaa的接口

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserBaseInfoService userBaseInfoService;

    @Override
    @GlobalTransactional  // 全局事务管理
    public void phoneRegister(PhoneRegisterDto userRegisterDto) {

        String mobile = userRegisterDto.getMobile();  // 手机号
        String password = userRegisterDto.getPassword(); // 密码
        Integer regChannel = userRegisterDto.getRegChannel(); // 注册渠道
        String smsCode = userRegisterDto.getSmsCode(); // 验证码

        // 校验

        // 校验手机号是否已被注册，根据手机号查询user表。
        Wrapper<User> wrapper =new EntityWrapper<>();
        // 参数一： 字段名  参数二：值
        wrapper.eq("phone",mobile);
        User user = selectOne(wrapper);
        if(user!=null){
            throw new RuntimeException("手机号已被注册");
        }

        // 验证码校验
        if(smsCode==null){
            throw new RuntimeException("验证码不能为空");
        }

        // 验证码是否过期
        String key = String.format(ValidationConstants.REDIS_KEY_SMS, mobile);
        VerifyCode verifyCode = (VerifyCode) redisTemplate.opsForValue().get(key);
        // 验证码是否正确
        if(verifyCode==null){
            throw new RuntimeException("验证码已过期,请重新获取");
        }
        if(!smsCode.equals(verifyCode.getCode())){
            throw new RuntimeException("验证码输入错误");
        }

        // 操作四张表
        //首先操作 t_login在uaa服务，需要openFeign
        Login login = new Login();
        login.setUsername(mobile);


        // 加密 自己实现
        login.setPassword(password); // 先不加密

        login.setType(Login.LOGIN_TYPE_USER);

        // 远程调用uaa，获取loginId
        JSONResult jsonResult = loginApi.phoneRegister(login);
        // 不确定是否可以获取到loginId, 因为是服务间的数据传输会把可能转化成二进制类型了
        Long loginId = Long.valueOf(jsonResult.getData().toString());

        long time = new Date().getTime();

        // 操作t_user   需要loginId
        user = new User();
        user.setPhone(mobile);
        user.setLoginId(loginId);
        user.setNickName(mobile);
        user.setCreateTime(time);

        // 插入操作
        insert(user);

//        int i = 1/0;

        // 操作t_user_account
        UserAccount userAccount = new UserAccount();
        userAccount.setId(user.getId());
        userAccount.setCreateTime(time);
        userAccountService.insert(userAccount);

        // 操作t_user_base_info
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(user.getId());
        userBaseInfo.setCreateTime(time);
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfoService.insert(userBaseInfo);
    }

//    @Override
//    @Transactional
//    public void deleteById1(Long id) {
//        deleteById(id);
//        int i = 1/0;
//    }
}
